package cn.tanglong.org.controller;

import cn.tanglong.basic.util.AjaxResult;
import cn.tanglong.basic.util.PageList;
import cn.tanglong.org.domain.Department;
import cn.tanglong.org.query.DepartmentQuery;
import cn.tanglong.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    // PathVariable 把收到的参数{id} 传给Long id
    // 这个id是占位符 随便写都可以 和下面的id对应
    @GetMapping("{id}")
    @ApiOperation(value = "查询某个部门",notes = "根据id查询")
    public Department findOne(@PathVariable("id") Long id){
        return departmentService.loadById(id);
    }

    @GetMapping
    @ApiOperation(value = "查询所有部门",notes = "查询所有信息")
    public List<Department> findAll(){
        return departmentService.loadAll();
    }

    // 分页查询
    // RequestBody 把请求体中的数据调整成json格式，封装到query中
    @PostMapping
    @ApiOperation(value = "查询分页",notes = "需要当前页和每页数据")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.queryList(query);
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除部门",notes = "根据id删除")
    public AjaxResult deleteById(@PathVariable("id") Long id){
        try {
            departmentService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            // 链式编程  装杯常用
            return AjaxResult.me().setMsg("操作失败");
        }
    }

    @PatchMapping
    @ApiOperation(value = "批量删除",notes = "根据id数组删除")
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            departmentService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            // 链式编程  装杯常用
            return AjaxResult.me().setMsg("操作失败");
        }
    }

    @PutMapping()
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改，没id就是添加")
    public AjaxResult addOrUpdateById(@RequestBody Department department){
        try {

            if (department.getId() == null) {

                departmentService.add(department);
            } else {

                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            // 链式编程  装杯常用
            return AjaxResult.me().setMsg("操作失败");
        }
    }

    @GetMapping("/tree")
    public List<Department> queryTree(){
        return departmentService.queryTree();
    }
}
